package cn.easy.rest.controller;

import cn.easy.api.FtpService;
import cn.easy.common.pojo.EasyResult;
import cn.easy.common.pojo.MyFile;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

@Controller
@RequestMapping(value = "/ftp")
public class FtpController {
    @Reference
    private FtpService ftpService;

    @ResponseBody
    @RequestMapping("/upload")
    public EasyResult uploadFile(MultipartFile file) {
        if(StringUtils.isEmpty(file.getOriginalFilename())){
            return new EasyResult(500,"fail","没有文件上传");
        }
        String TEMP_ENCODING = "ISO-8859-1";
       String DEFAULT_ENCODING = "UTF-8";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 专用于java对象序列化，将对象进行序列化
        ObjectOutputStream objectOutputStream = null;
        String serStr = null;
        try {
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(file);
            serStr = byteArrayOutputStream.toString(TEMP_ENCODING);
            serStr = java.net.URLEncoder.encode(serStr, DEFAULT_ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



        try {
           // byte[] bytes = "he".getBytes();
            String s = ftpService.uploadFile(serStr);
            return EasyResult.ok(s);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }
    }
}
